package com.leen.aspect.logdb;

import com.alibaba.fastjson.JSONArray;
import com.leen.aspect.annon.LogDB;
import com.leen.entity.Logs;
import com.leen.service.LogsService;
import com.leen.util.ThreadLocalUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 记录用户操作日志
 * @author wy
 */
@Component
@Aspect
@Order(1000000)
public class LogDBAspect {

    @Autowired
    private LogsService logsService;

    @Pointcut(value = "@annotation(com.leen.aspect.annon.LogDB) ")
    private void logExpress(){
    }


   @Around(value = "logExpress() && @annotation(logdb)")
    public Object aroundRecord(ProceedingJoinPoint  pjp, LogDB logdb) throws Throwable {

        //先执行方法
        Object value=pjp.proceed();

        //记录数据到数据
       Logs log=new Logs();
       log.setModuleType(logdb.module().getValue());
       log.setOperateType(logdb.operation().getValue());
       log.setOperateTime(new Date());
       //操作人  本地线程池
       String userName= ThreadLocalUser.getInstance().getCurrentUserName();
       log.setUserName(userName);
       log.setUserId(ThreadLocalUser.getInstance().getCurrentUserId());

       //收集参数
       String params= JSONArray.toJSONString(pjp.getArgs());
       log.setOperateContent(params);
       //写入数据库
       this.logsService.save(log);

        return value;
    }



}
